package com.qianbei.view.db;

import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;

/**
 * Created by bliu on 2018/3/14.
 */

public class DBUtil {
    //数据库存储路径
    String filePath = "data/data/com.qianbei.test/box.db";
    //数据库存放的文件夹 data/data/com.main.jh 下面
    String pathStr = "data/data/com.qianbei.test";

    SQLiteDatabase database;

    public SQLiteDatabase openDatabase(Context context) {
        File jhPath = new File(filePath);
        if (jhPath.exists()) {
            return SQLiteDatabase.openOrCreateDatabase(jhPath, null);
        } else {
            File path = new File(pathStr);
            if (path.mkdir()) {
                Log.i("test", "create dir success");
            } else {
                Log.i("test", "dir exists or fail");
            }

            try {
                AssetManager am = context.getAssets();
                InputStream is = am.open("box.db");
                FileOutputStream fos = new FileOutputStream(jhPath);

                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.flush();
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }

            return openDatabase(context);
        }
    }
}

